package net.siren93.smh.dao.impl;
import net.siren93.smh.dao.ProjectDao;
import net.siren93.smh.entity.ProjectEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by siren93 on 15/10/7.
 */
@Repository("projectDao")
public class ProjectDaoImpl implements ProjectDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public ProjectEntity findByName(String name) {
        String hql = "from ProjectEntity as entity where entity.name=:name";
        Query query = getCurrentSession().createQuery(hql);
        query.setString("name", name);
        List<ProjectEntity> list = query.list();
        if(list == null || list.size() == 0) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public ProjectEntity load(Integer id) {
        return (ProjectEntity)getCurrentSession().load(ProjectEntity.class, id);
    }

    @Override
    public ProjectEntity get(Integer id) {
        return (ProjectEntity)getCurrentSession().get(ProjectEntity.class, id);
    }

    @Override
    public List<ProjectEntity> findAll() {
        List<ProjectEntity> list = getCurrentSession().createQuery("from ProjectEntity").list();
        return list;
    }

    @Override
    public List<ProjectEntity> findByManager(int id, int page, int rows) {
        String hql = "from ProjectEntity as entity where entity.managerId=:id";
        Query query = getCurrentSession().createQuery(hql);
        query.setInteger("id", id);
        query.setFirstResult((page - 1) * rows);
        query.setMaxResults(rows);
        List<ProjectEntity> list = query.list();
        return list;
    }

    @Override
    public void persist(ProjectEntity entity) {
        getCurrentSession().persist(entity);
    }

    @Override
    public Integer save(ProjectEntity entity) {
        return (Integer)getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(ProjectEntity entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(Integer id) {
        ProjectEntity entity = load(id);
        getCurrentSession().delete(entity);
    }

    @Override
    public void flush() {
        getCurrentSession().flush();
    }
}
